<template>
  <div class="user-management">
    <el-card>
      <div class="section-title">用户管理</div>
      
      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="用户名">
            <el-input 
              v-model="filterForm.userName" 
              placeholder="请输入用户名" 
              clearable
              style="width: 200px;"
              class="center-input"
            />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input 
              v-model="filterForm.email" 
              placeholder="请输入邮箱" 
              clearable
              style="width: 200px;"
              class="center-input"
            />
          </el-form-item>
          <el-form-item label="角色">
            <el-select 
              v-model="filterForm.role" 
              placeholder="请选择角色" 
              clearable
              style="width: 150px;"
              :loading="roleOptionsLoading"
              class="center-input"
            >
              <el-option 
                v-for="role in roleOptions" 
                :key="role.id" 
                :label="role.roleName" 
                :value="role.roleName" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="filterForm.status" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px;"
              class="center-input"
            >
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              筛选
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-button 
        type="primary" 
        style="margin-bottom: 16px;" 
        @click="openAddDialog"
      >
        <el-icon style="margin-right: 4px;"><Plus /></el-icon>
        新增用户
      </el-button>
      
      <!-- 数据区域 -->
      <div class="data-area">
        <template v-if="loading">
          <el-skeleton :rows="6" animated style="margin: 32px 0;" />
        </template>
        <template v-else>
          <el-table 
            :row-key="(row,index)=>row.id" 
            :data="tableData" 
            style="width: 100%"  
            :loading="loading"
            :max-height="500"
          >
            <el-table-column prop="Index" label="序号" min-width="80" align="center">
              <template #default="scope">
                {{ currentPage.page>1?currentPage.page*10-10+scope.$index + 1: scope.$index+1 }}
              </template>
            </el-table-column>
            <el-table-column prop="userName" label="用户名" min-width="200" align="center">
              <template #default="scope">
                <div class="user-info-cell" :class="{ 'editing': editingRowId === scope.row.id }">
                  <div class="user-avatar-wrapper">
                    <el-avatar :size="32" :src="getUserAvatar(scope.row)" class="user-avatar">
                      <el-icon><UserFilled /></el-icon>
                    </el-avatar>
                  </div>
                  <div class="user-details">
                    <div class="user-name-wrapper">
                      <el-input 
                        v-if="editingRowId === scope.row.id" 
                        v-model="scope.row.userName" 
                        placeholder="请输入用户名"
                        class="edit-input center-input"
                        size="small"
                      />
                      <span v-else class="user-name-text">{{ scope.row.userName }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="email" label="邮箱" min-width="220" align="center">
              <template #default="scope">
                <el-input v-if="editingRowId === scope.row.id" v-model="scope.row.email" placeholder="请输入邮箱" class="center-input" />
                <span v-else>{{ scope.row.email }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="电话" min-width="150" align="center">
              <template #default="scope">
                <el-input v-if="editingRowId === scope.row.id" v-model="scope.row.phone" placeholder="请输入电话" class="center-input" />
                <span v-else>{{ scope.row.phone }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="role" label="角色" min-width="120" align="center">
              <template #default="scope">
                <div class="role-tags-container">
                  <el-tooltip 
                    v-if="getValidRoles(scope.row).length > 2" 
                    :content="getRoleDisplay(scope.row)" 
                    placement="top"
                    :show-after="200"
                  >
                    <div class="role-tags-wrapper">
                      <el-tag 
                        v-for="(role, index) in getValidRoles(scope.row).slice(0, 2)" 
                        :key="index"
                        size="small"
                        :type="getRoleTagType(role)"
                        class="role-tag"
                      >
                        {{ role }}
                      </el-tag>
                      <el-tag 
                        v-if="getValidRoles(scope.row).length > 2"
                        size="small"
                        type="info"
                        class="role-tag more-tag"
                      >
                        +{{ getValidRoles(scope.row).length - 2 }}
                      </el-tag>
                    </div>
                  </el-tooltip>
                  <div v-else class="role-tags-wrapper">
                    <el-tag 
                      v-for="(role, index) in getValidRoles(scope.row)" 
                      :key="index"
                      size="small"
                      :type="getRoleTagType(role)"
                      class="role-tag"
                    >
                      {{ role }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="isActive" label="状态" min-width="100" align="center">
              <template #default="scope">
                <template v-if="editingRowId === scope.row.id">
                  <el-switch v-model="scope.row.isActive" />
                </template>
                <template v-else>
                  <el-tag v-if="scope.row.isActive === true" type="success">启用</el-tag>
                  <el-tag v-else type="danger">禁用</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="200" align="center">
              <template #default="scope">
                <template v-if="editingRowId !== scope.row.id">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="openEdit(scope.row.id)" 
                    link
                  >
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button 
                    type="info" 
                    size="small" 
                    link 
                    @click="openRoleDialog(scope.row.id)"
                  >
                    <el-icon><User /></el-icon>
                    角色
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="openDelete(scope.$index)" 
                    link
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template> 
                <template v-else>
                  <el-button type="success" size="small" @click="saveEdit(scope.row.id)" link>
                    <el-icon><Check /></el-icon>
                    保存
                  </el-button>
                  <el-button type="warning" size="small" @click="cancelEdit()" link>
                    <el-icon><Close /></el-icon>
                    取消
                  </el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <template v-if="loading">
          <el-skeleton :rows="1" animated style="width: 400px; height: 50px;" />
        </template>
        <template v-else>
          <el-pagination
            :background="background"
            layout="sizes, prev, pager, next, jumper"
            :total="totalSize"
            v-model:current-page="currentPage.page"
            v-model:page-size="currentPage.pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :disabled="false"
            :class="{ 'pagination-disabled': isDialogOpen }"
          />
        </template>
      </div>
    </el-card>










    <!-- 新增用户对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增用户" width="500px" :close-on-click-modal="false" @close="isDialogOpen = false">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px" class="add-user-form">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addForm.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" placeholder="请输入密码" show-password clearable />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱地址" clearable />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入电话号码" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false" size="large">取消</el-button>
          <el-button type="primary" @click="handleAddUser" size="large" :loading="addLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 分配角色对话框 -->
    <el-dialog 
      v-model="dialogRoleVisible" 
      title="分配角色" 
      width="700px" 
      :close-on-click-modal="false" 
      top="5vh"
      :lock-scroll="false"
    >
      <div class="assign-roles-content">
        <div class="user-info">
          <div class="user-avatar-info">
            <el-avatar :size="40" :src="getUserAvatar(currentUser)">
              <el-icon><UserFilled /></el-icon>
            </el-avatar>
            <div class="user-details-info">
              <h4>{{ currentUser?.userName }}</h4>
              <p>{{ currentUser?.email || '暂无邮箱' }}</p>
            </div>
          </div>
          <div class="current-roles">
            <h5>当前角色</h5>
            <div class="current-roles-tags">
              <el-tooltip 
                v-if="getValidRoles(currentUser).length > 2" 
                :content="getRoleDisplay(currentUser)" 
                placement="top"
                :show-after="200"
              >
                <div class="role-tags-wrapper">
                  <el-tag 
                    v-for="role in getValidRoles(currentUser).slice(0, 2)" 
                    :key="role"
                    size="small"
                    :type="getRoleTagType(role)"
                    class="role-tag"
                  >
                    {{ role }}
                  </el-tag>
                  <el-tag 
                    v-if="getValidRoles(currentUser).length > 2"
                    size="small"
                    type="info"
                    class="role-tag more-tag"
                  >
                    +{{ getValidRoles(currentUser).length - 2 }}
                  </el-tag>
                </div>
              </el-tooltip>
              <div v-else class="role-tags-wrapper">
                <el-tag 
                  v-for="role in getValidRoles(currentUser)" 
                  :key="role"
                  size="small"
                  :type="getRoleTagType(role)"
                  class="role-tag"
                >
                  {{ role }}
                </el-tag>
              </div>
              <span v-if="getValidRoles(currentUser).length === 0" class="no-roles">暂无角色</span>
            </div>
          </div>
        </div>

        <div class="roles-section">
          <div class="section-header">
            <h5>选择角色</h5>
            <span class="selected-count">已选择 {{ roleList.length }} 个角色</span>
          </div>

          <div class="roles-container">
            <el-checkbox-group v-model="roleList" class="roles-list">
              <el-checkbox
                v-for="role in checkList"
                :key="role.id"
                :label="role.id"
                class="role-item"
                :style="{ height: '80px', minHeight: '80px', maxHeight: '80px' }"
              >
                <template #default>
                  <div class="role-info">
                    <span class="role-name">{{ role.roleName }}</span>
                    <span class="role-desc">{{ role.description || '暂无描述' }}</span>
                  </div>
                </template>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogRoleVisible = false" size="large">取消</el-button>
          <el-button type="primary" @click="handleAssignRoles" size="large" :loading="roleLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="deleteDialogVisible" title="删除用户" width="400px" :close-on-click-modal="false" @close="isDialogOpen = false">
      <div class="delete-confirm">
        <div class="delete-icon">
          <el-icon size="48" color="#f56c6c"><Warning /></el-icon>
        </div>
        <div class="delete-message">
          <h3>确定要删除该用户吗？</h3>
          <p>此操作不可恢复，请谨慎操作。</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false" size="large">取消</el-button>
          <el-button type="danger" @click="handleDeleteUser" size="large" :loading="deleteLoading">删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: 'UserIndex'
})

import { ref, onMounted } from 'vue'
import { usePermission } from '@/composables/usePermission'
import { getUserListPage, addUser, updateUser, deleteUser, enableUser, disableUser, assignRoles, getRoleList, getUserRoles} from '@/api/user'
import { ElMessage } from 'element-plus'
import { baseURL } from '@/utils/request.js'
import { handleApiError } from '@/utils/errorHandler'
import { UserFilled } from '@element-plus/icons-vue'
import { Edit, User, Delete, Check, Close, Warning, Search, Refresh, Plus } from '@element-plus/icons-vue'

let checkList=ref([])
let dialogRoleVisible=ref(false)
const tableData = ref([])
const { handlePermissionDenied } = usePermission()

const loading = ref(true)
const currentPage = ref({ page: 1, pageSize: 10 })
const background = ref(true)

// 筛选相关
const filterForm = ref({
  userName: '',
  email: '',
  role: '',
  status: ''
})

// 角色选项相关
const roleOptions = ref([])
const roleOptionsLoading = ref(false)

// 新增用户相关
const addDialogVisible = ref(false)
const addForm = ref({ userName: '', password: '', email: '', phone: ''})
const addFormRef = ref()
const addLoading = ref(false)
const roleLoading = ref(false)
const deleteLoading = ref(false)
const isDialogOpen = ref(false)
const addRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

let totalSize = ref(0)
const editingRowId = ref(null)
let backupRow = null

function openAddDialog() {
  addDialogVisible.value = true
  isDialogOpen.value = true
  addForm.value = { userName: '', password: '', email: '', phone: ''}
}

async function handleAddUser() {
  await addFormRef.value.validate()
  addLoading.value = true
  try {
    // 构造新增用户的数据，确保字段名与后端一致
    const createData = {
      username: addForm.value.userName, // 注意：后端期望的是username，不是userName
      password: addForm.value.password,
      email: addForm.value.email,
      phone: addForm.value.phone
    }
    
    await addUser(createData)
    ElMessage.success('新增用户成功')
    addDialogVisible.value = false
    isDialogOpen.value = false
    
    // 重新加载用户列表
    let response = await getUserListPage(currentPage.value)
    if (response && response.data) {
      tableData.value = response.data.items || []
      totalSize.value = response.data.total || 0
    }
  } catch (error) {
    if (error.response && error.response.status === 403) {
      handlePermissionDenied(error, { showMessage: true })
    } else {
      handleApiError(error, { showMessage: true })
    }
  } finally {
    addLoading.value = false
  }
}

function openEdit(id) {
  editingRowId.value = id
  const row = tableData.value.find(item => item.id === id || item.Id === id)
  backupRow = { ...row }
}

let saveEdit=async(id)=> {
  let editUser=tableData.value.find(item=>item.id===id)
  
  try {
    // 先更新用户基本信息
    const updateData = {
      id: editUser.id,
      userName: editUser.userName,
      email: editUser.email,
      phone: editUser.phone
    }
    
    await updateUser(updateData)
    
    // 如果状态有变化，使用专门的启用/禁用API
    if (backupRow && backupRow.isActive !== editUser.isActive) {
      if (editUser.isActive) {
        await enableUser(editUser.id)
      } else {
        await disableUser(editUser.id)
      }
    }
    
    ElMessage.success("更新用户成功")
    editingRowId.value = null
    
    // 重新加载用户列表以获取最新数据
    let response = await getUserListPage(currentPage.value)
    if (response && response.data) {
      tableData.value = response.data.items || []
      totalSize.value = response.data.total || 0
    }
  } catch (error) {
    if (error.response && error.response.status === 403) {
      handlePermissionDenied(error, { showMessage: true })
    } else {
      handleApiError(error, { showMessage: true })
    }
  }
}

function cancelEdit() {
  if (editingRowId.value !== null && backupRow) {
    const idx = tableData.value.findIndex(item => item.id === editingRowId.value || item.Id === editingRowId.value)
    if (idx !== -1) {
      Object.assign(tableData.value[idx], backupRow)
    }
  }
  editingRowId.value = null
  backupRow = null
}

let deleteDialogVisible = ref(false)
let deleteIndex = -1

let openDelete=async(index) =>{
  deleteIndex = index
  deleteDialogVisible.value = true
  isDialogOpen.value = true
}

async function handleDeleteUser() {
  deleteLoading.value = true
  const id = tableData.value[deleteIndex].id || tableData.value[deleteIndex].Id
  try {
    await deleteUser(id)
    
    // 重新加载用户列表
    let response = await getUserListPage(currentPage.value)
    if (response && response.data) {
      tableData.value = response.data.items || []
      totalSize.value = response.data.total || 0
    }
    
    ElMessage.success("删除用户成功")
    deleteDialogVisible.value = false
  } catch (error) {
    if (error.response && error.response.status === 403) {
      handlePermissionDenied(error, { showMessage: true })
    } else {
      handleApiError(error, { showMessage: true })
    }
  } finally {
    deleteLoading.value = false
  }
}

// 筛选相关函数
function handleFilter() {
  currentPage.value.page = 1
  fetchUserList()
}

function resetFilter() {
  filterForm.value = {
    userName: '',
    email: '',
    role: '',
    status: ''
  }
  currentPage.value.page = 1
  fetchUserList()
}

// 获取角色选项
async function fetchRoleOptions() {
  roleOptionsLoading.value = true;
  try {
    const response = await getRoleList()
    
    if (response && response.data) {
      roleOptions.value = response.data || [];
    } else {
      console.error('角色选项数据格式错误:', response);
      roleOptions.value = [];
    }
  } catch (error) {
    console.error('加载角色选项失败:', error);
    if (error.response && error.response.status === 403) {
      handlePermissionDenied(error, { showMessage: false });
    } else {
      handleApiError(error, { showMessage: false });
    }
    roleOptions.value = [];
  } finally {
    roleOptionsLoading.value = false;
  }
}

// 修改fetchUserList函数以支持筛选
async function fetchUserList(showLoading = true) {
  
  if (showLoading) {
    loading.value = true
  }
  try {
    // 构建API参数，包含筛选条件
    const params = {
      page: currentPage.value.page,
      size: currentPage.value.pageSize
    }
    
    // 构建搜索字符串
    let searchTerms = [];
    if (filterForm.value.userName) {
      searchTerms.push(filterForm.value.userName);
    }
    if (filterForm.value.email) {
      searchTerms.push(filterForm.value.email);
    }
    if (searchTerms.length > 0) {
      params.search = searchTerms.join(' ');
    }
    
    const response = await getUserListPage(params)
    
    if (response && response.data) {
      let users = [];
      let total = 0;
      
      if (response.data.items) {
        // 分页格式数据
        users = response.data.items;
        total = response.data.total || 0;
      } else if (Array.isArray(response.data)) {
        // 数组格式数据
        users = response.data;
        total = response.data.length;
      }
      
      // 为每个用户获取角色信息（如果用户数据中没有角色信息）
      for (let user of users) {
        if (!user.roles || user.roles.length === 0) {
          try {
            const rolesResponse = await getUserRoles(user.id || user.Id);
            if (rolesResponse && rolesResponse.data) {
              // 确保角色数据格式正确，后端返回的是RoleDto对象数组
              user.roles = rolesResponse.data.map(role => {
                if (typeof role === 'string') {
                  return role;
                } else if (typeof role === 'object' && role !== null) {
                  return role.roleName || role.name || role.role || role.displayName || '未知角色';
                }
                return '未知角色';
              }).filter(role => role && role.trim() !== '');
            } else {
              user.roles = [];
            }
          } catch (error) {
            console.warn(`获取用户 ${user.userName} 的角色信息失败:`, error);
            user.roles = [];
          }
        }
      }
      
      // 前端状态筛选
      if (filterForm.value.status) {
        const isActive = filterForm.value.status === 'active';
        const beforeStatusFilter = users.length;
        users = users.filter(user => user.isActive === isActive);
        const afterStatusFilter = users.length;
        console.log(`状态筛选: ${beforeStatusFilter} -> ${afterStatusFilter}`);
        total = users.length; // 重新计算总数
      }
      
      // 前端角色筛选
      if (filterForm.value.role) {
        
        users = users.filter(user => {
          const userRoles = getValidRoles(user);
          if (userRoles.length === 0) {
            return false;
          }
          
          const hasRole = userRoles.some(role => 
            role.toLowerCase() === filterForm.value.role.toLowerCase()
          );
          
      
          return hasRole;
        });
        
        total = users.length; // 重新计算总数
      }
      
      tableData.value = users;
      totalSize.value = total;
      
    } else {
      tableData.value = []
      totalSize.value = 0
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    if (error.response && error.response.status === 403) {
      handlePermissionDenied(error, { showMessage: true })
    } else {
      handleApiError(error, { showMessage: true })
    }
    tableData.value = []
    totalSize.value = 0
  } finally {
    if (showLoading) {
      loading.value = false
    }
  }
}

onMounted(async () => {
  loading.value = true
  try {
    // 使用fetchUserList函数来确保筛选参数正确传递
    await fetchUserList()
    
    // 获取角色列表用于分配角色对话框
    let res = await getRoleList()
    checkList.value = res.data || []
    
    // 获取角色选项用于筛选
    await fetchRoleOptions()
  } catch (error) {
    console.error('加载用户列表失败:', error)
    handleApiError(error, { showMessage: true })
    tableData.value = []
    totalSize.value = 0
  } finally {
    loading.value = false
  }
})



let handleCurrentChange = async (page) => {
  currentPage.value.page = page
  // 分页切换时不显示加载动画
  await fetchUserList(false)
}

let handleSizeChange=async(size)=>{
  currentPage.value.pageSize = size
  currentPage.value.page = 1
  // 分页切换时不显示加载动画
  await fetchUserList(false)
}

function getUserAvatar(user) {
  if (user && user.avatar) {
    return `${baseURL}/users/avatar/${user.avatar}`
  }
  return ''
}

let currentUserId = ref(null)
let currentUser = ref(null)

let openRoleDialog=async(id)=>{
  dialogRoleVisible.value=true
  isDialogOpen.value = true
  currentUserId.value = id
  
  const user = tableData.value.find(u => u.id === id)
  currentUser.value = user
  
  roleLoading.value = true
  try {
    const [roleListRes, userRolesRes] = await Promise.all([
      getRoleList(),
      getUserRoles(id)
    ])
    
    // 确保数据格式正确
    checkList.value = roleListRes.data || []
    roleList.value = (userRolesRes.data || []).map(role => role.id)
  } catch (error) {
    console.error('加载角色数据失败:', error)
    handleApiError(error, { showMessage: true })
    dialogRoleVisible.value = false
  } finally {
    roleLoading.value = false
  }
}

let roleList=ref([])
let handleAssignRoles=async()=>{
  roleLoading.value = true
  try {
    await assignRoles(currentUserId.value, roleList.value)
    
    dialogRoleVisible.value = false
    ElMessage.success('分配角色成功')
    
    // 重新加载用户列表
    let response = await getUserListPage(currentPage.value)
    if (response && response.data) {
      tableData.value = response.data.items || []
      totalSize.value = response.data.total || 0
    }
  } catch (error) {
    handleApiError(error, { showMessage: true })
  } finally {
    roleLoading.value = false
  }
}

function getRoleDisplay(row) {
  const validRoles = getValidRoles(row);
  if (validRoles.length === 0) {
    return '无角色';
  }
  return validRoles.join('、');
}

function getValidRoles(row) {
  if (!row.roles || row.roles.length === 0) {
    return [];
  }
  
  // 确保角色名称是字符串，并且不是空字符串
  const validRoles = Array.isArray(row.roles) ? row.roles.filter(role => 
    typeof role === 'string' && role.trim() !== ''
  ) : [];
  
  // 对角色进行排序，管理员角色优先显示
  const rolePriority = {
    '超级管理员': 1,
    '管理员': 2,
    '系统管理员': 3,
    '角色管理员': 4,
    '权限管理员': 5,
    '普通用户': 6,
    '用户': 7
  };
  
  const sortedRoles = validRoles.sort((a, b) => {
    const priorityA = rolePriority[a] || 999;
    const priorityB = rolePriority[b] || 999;
    return priorityA - priorityB;
  });
  
  return sortedRoles;
}

// 根据角色名称获取标签类型
function getRoleTagType(roleName) {
  const roleTypeMap = {
    '管理员': 'danger',
    '超级管理员': 'danger',
    '普通用户': 'info',
    '用户': 'info',
    '角色管理员': 'warning',
    '权限管理员': 'warning',
    '系统管理员': 'danger'
  }
  const tagType = roleTypeMap[roleName] || 'primary'
  return tagType
}


</script>

<style scoped>
.user-management {
  padding: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 18px;
  color: #303133;
}

/* 数据区域样式 */
.data-area {
  flex: 1;
  overflow: visible;
  padding-right: 10px;
  padding-bottom: 0;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.data-area .el-table {
  width: 100%;
  height: auto;
  overflow: visible;
  margin-bottom: 0;
  border: none;
}

.data-area .el-table__body-wrapper {
  overflow-y: auto;
  max-height: 500px;
}

/* 分页区域样式 */
.pagination-area {
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px 0;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  min-height: 60px;
  width: 100%;
  position: relative;
  z-index: 10;
  margin-top: 8px;
}

/* 表格样式 */
.el-table {
  font-size: 14px;
}

.el-table .el-table__row {
  height: 56px;
}

.el-table .el-table__row td {
  vertical-align: middle;
  padding: 8px 0;
}

.el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
  vertical-align: middle;
}

.el-table td {
  padding: 8px 0;
  vertical-align: middle;
  height: 56px;
}

.el-table .el-table__cell {
  vertical-align: middle;
}

/* 确保表格可以滚动 */
.el-table__body-wrapper {
  overflow-y: auto !important;
}

.el-table__body {
  overflow: visible !important;
}

/* 按钮样式 */
.el-button--small {
  font-size: 12px;
  padding: 5px 11px;
}

/* 标签样式 */
.el-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  background: #fff !important;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 20px 15px;
  background: #fff !important;
}

:deep(.el-dialog__body) {
  padding: 20px;
  background: #fff !important;
}

:deep(.el-dialog__footer) {
  border-top: none;
  padding: 15px 20px 20px;
  background: #fff !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: 18px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 新增用户表单样式 */
.add-user-form {
  padding: 20px 0;
}

.add-user-form .el-form-item {
  margin-bottom: 20px;
}

.add-user-form .el-input {
  width: 100%;
}

.add-user-form .el-form-item__label {
  font-weight: 500;
  color: var(--text-color);
}

/* 输入框样式 */
.el-input__inner {
  border-radius: 4px;
}

/* 开关样式 */
.el-switch {
  margin: 0;
}

/* 加载状态 */
.el-skeleton {
  margin: 20px 0;
}

/* 用户信息单元格样式 */
.user-info-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  height: 100%;
  min-height: 48px;
  padding: 4px 0;
  width: 100%;
}

.user-avatar-wrapper {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
}

.user-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.user-details {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.user-name-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.user-name-text {
  font-weight: 500;
  color: #303133;
  line-height: 1.4;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

.edit-input {
  width: 100%;
}



/* 删除确认对话框样式 */
.delete-confirm {
  text-align: center;
  padding: 20px 0;
}

.delete-icon {
  margin-bottom: 16px;
}

.delete-message h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.delete-message p {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

/* 角色标签样式 */
.role-tags-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.role-tags-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.role-tag {
  margin: 0;
  font-size: 11px;
  height: 20px;
  line-height: 18px;
  padding: 0 6px;
  border-radius: 10px;
  white-space: nowrap;
  flex-shrink: 0;
}

.role-tag.more-tag {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
}

.role-tag:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 分配角色对话框样式 */
.assign-roles-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}

.user-info {
  background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  color: white;
  flex-shrink: 0;
}

.user-avatar-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.user-details-info p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.roles-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.section-header {
  background: #f5f7fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  padding: 12px 16px;
  margin-bottom: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.section-header h5 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.selected-count {
  font-size: 14px;
  color: #409eff;
  font-weight: 500;
}

.roles-container {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.roles-list {
  padding: 16px;
  background: #ffffff;
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 12px;
}

.role-item {
  margin: 0 !important;
  padding: 12px !important;
  border: 1px solid #e4e7ed !important;
  border-radius: 6px !important;
  background: #fff !important;
  transition: all 0.3s ease !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05) !important;
}

.role-item:hover {
  border-color: #409eff !important;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15) !important;
  transform: translateY(-1px) !important;
}

.role-item.is-checked {
  border-color: #409eff !important;
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f7ff 100%) !important;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2) !important;
}

.role-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 100%;
}

.role-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
  line-height: 1.4;
}

.role-desc {
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

/* 当前角色样式 */
.current-roles {
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.current-roles h5 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.current-roles-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.current-roles-tags .role-tag {
  margin: 0;
}

.current-roles-tags .role-tags-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
}

.no-roles {
  color: #909399;
  font-size: 12px;
  font-style: italic;
}

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  justify-content: flex-start;
  margin: 0;
}

.filter-form .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

.filter-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
  padding-right: 8px;
}

.filter-form .el-input__wrapper {
  border-radius: 4px;
  border-color: #dcdfe6;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.filter-form .el-input__wrapper:hover {
  border-color: #c0c4cc;
}

.filter-form .el-input__wrapper.is-focus {
  border-color: #409eff;
  box-shadow: 0 0 0 1px #409eff inset;
}

.filter-form .el-select .el-input__wrapper {
  border-radius: 4px;
  border-color: #dcdfe6;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.filter-form .el-select .el-input__wrapper:hover {
  border-color: #c0c4cc;
}

.filter-form .el-select .el-input__wrapper.is-focus {
  border-color: #409eff;
  box-shadow: 0 0 0 1px #409eff inset;
}

.filter-form .el-button {
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.filter-form .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.filter-form .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.filter-form .el-button--default {
  background-color: #ffffff;
  border-color: #dcdfe6;
  color: #606266;
}

.filter-form .el-button--default:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 10px;
    margin-left: 0; /* 移除左边距，因为侧边栏被隐藏了 */
    margin-top: 0; /* 移除顶部边距，因为主布局已经处理了 */
  }
  
  .section-title {
    font-size: 16px;
  }
  
  .data-area {
    padding-right: 5px;
  }
  
  .roles-list {
    grid-template-columns: 1fr;
  }

  .role-tags-wrapper {
    gap: 2px;
  }
  
  .role-tag {
    font-size: 10px;
    height: 18px;
    line-height: 16px;
    padding: 0 4px;
  }
}

@media (max-width: 480px) {
  .user-management {
    margin-left: 0;
    margin-top: 0; /* 移除顶部边距 */
    padding: 5px;
  }
}

/* 表格样式优化 */
.data-area .el-table {
  border: none;
}

.data-area .el-table th.el-table__cell {
  border-right: none;
  border-bottom: 1px solid #ebeef5;
}

.data-area .el-table td.el-table__cell {
  border-right: none;
  border-bottom: 1px solid #ebeef5;
}

.data-area .el-table--border {
  border: none;
}

.data-area .el-table--border::after {
  display: none;
}

.data-area .el-table--border .el-table__inner-wrapper::after {
  display: none;
}

.data-area .el-table--border .el-table__border-left-patch {
  display: none;
}

/* 新增用户对话框样式 */
.add-user-form :deep(.el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.add-user-form :deep(.el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.add-user-form :deep(.el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

.add-user-form :deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* 对话框标题样式 */
:deep(.el-dialog__title) {
  font-weight: 600 !important;
  font-size: 18px !important;
  letter-spacing: 0.5px !important;
}

/* 对话框标题底部边框 */
:deep(.el-dialog__header) {
  border-bottom: 1px solid #e4e7ed !important;
  padding-bottom: 15px !important;
  margin-bottom: 20px !important;
}

/* 筛选区域输入框样式 */
.filter-form :deep(.el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.filter-form :deep(.el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.filter-form :deep(.el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

.filter-form :deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* 筛选区域下拉框样式 */
.filter-form :deep(.el-select .el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.filter-form :deep(.el-select .el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.filter-form :deep(.el-select .el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

/* 表格内输入框居中样式 */
.center-input :deep(.el-input__inner) {
  text-align: center !important;
}

/* 确保编辑状态下的输入框内容居中 */
.edit-input.center-input :deep(.el-input__inner) {
  text-align: center !important;
}

/* 表格内所有输入框居中 */
.data-area .el-table .center-input :deep(.el-input__inner) {
  text-align: center !important;
}

/* 表格内编辑输入框样式 - 只有下边框线 */
.data-area .el-table .center-input :deep(.el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.data-area .el-table .center-input :deep(.el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.data-area .el-table .center-input :deep(.el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

.data-area .el-table .center-input :deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}
</style>